<?php

namespace App\Console\Commands\WorkOrder;

use App\Enums\WorkOrder\MissionEnum;
use App\Enums\WorkOrder\OrderEnum;
use App\Models\WorkOrder\WorkOrderApplyMainModel;
use App\Models\WorkOrder\WorkOrderApplyManagerModel;
use App\Models\WorkOrder\WorkOrderApplyManagerSubmitHistoryModel;
use App\Models\WorkOrder\WorkOrderOperateLogModel;
use App\Models\WorkOrder\WorkOrderUserRoleModel;
use App\Remote\Rms\RmsUserRemote;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;

class OperateLogGenerateCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'workOrder:OperateLogGenerate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '工单：生成操作日志';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     */
    public function handle(): int
    {
        WorkOrderApplyMainModel::query()->with(
            ["managerRel"]
        )->where(
            "step", ">", MissionEnum::STEP_1
        )->chunkById("100", function (Collection $workOrderCollection) {
            $workOrderOperateLogData = $applyManagerSubmitData = [];

            $workOrderCollection->each(function (WorkOrderApplyMainModel $applyMainModel) use (
                &$workOrderOperateLogData,
                &$applyManagerSubmitData
            ) {
                $uids = $applyMainModel->managerRel->pluck("managerId")->merge([$applyMainModel->createdByUid])
                                                   ->toArray();
                try {
                    $rmsUserInfo = RmsUserRemote::getRmsUserByIds($uids);
                } catch (\Exception $exception) {
                    $rmsUserInfo = [];
                }
                $rmsUserInfoIdIndex = collect($rmsUserInfo)->keyBy("id");
                $applyMainModel->managerRel->each(function (WorkOrderApplyManagerModel $applyManagerModel) use (
                    &$workOrderOperateLogData,
                    &$applyManagerSubmitData,
                    $applyMainModel,
                    $rmsUserInfoIdIndex
                ) {
                    $step = $remarkType = $solutionType = null;
                    switch ($applyManagerModel->role) {
                        case  WorkOrderUserRoleModel::ROLE_TYPE_1:
                        case WorkOrderUserRoleModel::ROLE_TYPE_6:
                            $step         = MissionEnum::STEP_2;
                            $remarkType   = WorkOrderOperateLogModel::TYPE_4;
                            $solutionType = WorkOrderOperateLogModel::TYPE_3;
                            array_push($workOrderOperateLogData, [
                                "workOrderNo"     => $applyManagerModel->workOrderNo,
                                "step"            => MissionEnum::STEP_1,
                                "type"            => WorkOrderOperateLogModel::TYPE_1,
                                "content"         => "工单提交",
                                "createdByUid"    => $applyMainModel->createdByUid,
                                "createdUsername" => attributeGet($rmsUserInfoIdIndex,
                                    "{$applyMainModel->createdByUid}.username", ""),
                                "createdAt"       => $applyMainModel->createdAt->timestamp
                            ]);
                            break;
                        case WorkOrderUserRoleModel::ROLE_TYPE_7:
                            $step = MissionEnum::STEP_4;
                            break;
                        default:
                            if ($applyMainModel->isFunctionWaiMaiOpen()) {
                                $step         = MissionEnum::STEP_5;
                                $remarkType   = WorkOrderOperateLogModel::TYPE_8;
                                $solutionType = WorkOrderOperateLogModel::TYPE_7;
                            } else {
                                if ($applyMainModel->problemChildId == OrderEnum::PROBLEM_PID_5_CHILDREN_105) {

                                } else {
                                    $step         = MissionEnum::STEP_4;
                                    $remarkType   = WorkOrderOperateLogModel::TYPE_6;
                                    $solutionType = WorkOrderOperateLogModel::TYPE_5;
                                }
                            }
                            break;
                    }

                    if ($step) {
                        $createdUsername = attributeGet(
                            $rmsUserInfoIdIndex,
                            "{$applyManagerModel->managerId}.username",
                            ""
                        );
                        if (!empty(trim($applyManagerModel->remark, "-"))) {
                            array_push($workOrderOperateLogData, [
                                "workOrderNo"     => $applyManagerModel->workOrderNo,
                                "step"            => MissionEnum::STEP_4,
                                "type"            => $remarkType,
                                "content"         => $applyManagerModel->remark,
                                "createdByUid"    => $applyManagerModel->createdByUid,
                                "createdUsername" => $createdUsername,
                                "createdAt"       => $applyManagerModel->createdAt->timestamp
                            ]);

                            array_push($applyManagerSubmitData, [
                                "type"            => WorkOrderApplyManagerSubmitHistoryModel::TYPE_REMARK,
                                "applyManagerId"  => $applyManagerModel->id,
                                "content"         => $applyManagerModel->remark,
                                "createdByUid"    => $applyManagerModel->createdByUid,
                                "createdUsername" => $createdUsername,
                                "createdAt"       => $applyManagerModel->createdAt->timestamp
                            ]);
                        }
                        if (!empty(trim($applyManagerModel->solution, "-"))) {
                            array_push($workOrderOperateLogData, [
                                "workOrderNo"     => $applyManagerModel->workOrderNo,
                                "step"            => MissionEnum::STEP_4,
                                "type"            => $solutionType,
                                "content"         => $applyManagerModel->solution,
                                "createdByUid"    => $applyManagerModel->createdByUid,
                                "createdUsername" => $createdUsername,
                                "createdAt"       => $applyManagerModel->createdAt->timestamp
                            ]);
                            array_push($applyManagerSubmitData, [
                                "type"            => WorkOrderApplyManagerSubmitHistoryModel::TYPE_SOLUTION,
                                "applyManagerId"  => $applyManagerModel->id,
                                "content"         => $applyManagerModel->solution,
                                "createdByUid"    => $applyManagerModel->createdByUid,
                                "createdUsername" => $createdUsername,
                                "createdAt"       => $applyManagerModel->createdAt->timestamp
                            ]);
                        }
                    }
                });

                if ($applyMainModel->step == MissionEnum::STEP_99) {
                    $applyMainModel->update([
                        "merchantConfirmFinishTime"   => time(),
                        "merchantConfirmFinishStatus" => 1,
                        "merchantConfirmFinishType"   => WorkOrderApplyMainModel::MERCHANT_CONFIRM_FINISH_TYPE_SYSTEM
                    ]);
                }
            });
            if (!empty($workOrderOperateLogData)) {
                WorkOrderOperateLogModel::query()->insert($workOrderOperateLogData);
            }
            if (!empty($applyManagerSubmitData)) {
                WorkOrderApplyManagerSubmitHistoryModel::query()->insert($applyManagerSubmitData);
            }
        });
        return 0;
    }
}
